#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

pthread_mutex_t mutex;
pthread_cond_t a;
pthread_cond_t b;

void* A(void* arg)
{
    const char* msg = (char*)arg;
    while(1)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&a,&mutex);
        sleep(1);
        printf("%s\n",msg);
        pthread_mutex_unlock(&mutex);
        pthread_cond_signal(&b);
    }
}

void* B(void* arg)
{
    const char* msg = (char*)arg;
    while(1)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&b,&mutex);
        sleep(1);
        printf("%s\n",msg);
        pthread_mutex_unlock(&mutex);
        pthread_cond_signal(&a);
    }
}

int main()
{
    pthread_mutex_init(&mutex,NULL);
    pthread_cond_init(&a, NULL);
    pthread_cond_init(&b, NULL);

    pthread_t p1,p2;

    pthread_create(&p1,NULL,A,"i am process A");
    pthread_create(&p2,NULL,B,"i am process B");

    pthread_mutex_lock(&mutex);
    pthread_cond_signal(&a);
    pthread_mutex_unlock(&mutex);

    pthread_join(p1,NULL);
    pthread_join(p2,NULL);

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&a);
    pthread_cond_destroy(&b);

    return 0;
}